import { ClassifyApi, fetchClassify } from '@/api/premium/category/classify'
import { ClassifyType } from '@/api/premium/category/model/classifyModel'
import {
  MaterialApi,
  searchTagList,
  updateMatV2,
} from '@/api/premium/content/material'
import { UpdateMaterialReq } from '@/api/premium/content/model/materialModel'
import { OptionTagReq } from '@/api/premium/content/model/tagModel'
import { optionTag, TagApi } from '@/api/premium/content/tag'
import {
  MaterialItem,
  MaterialSecType,
  MaterialStucture,
  MaterialType,
  MaterialUsage,
} from '@/components/ItemList/MaterialList/types'
import { useStore } from '@/store'
import { compareObject } from '@/utils/objectHelper'
import { message } from 'ant-design-vue'
import { cloneDeep, debounce } from 'lodash-es'
import { computed, reactive, nextTick, Ref } from 'vue'
import { EditMatInfoDiaForm, EditMatInfoDiaState } from '../types'

const useEditMatInfoDia = (searchApi: AsyncFun) => {
  const store = useStore()
  let oldFormData: EditMatInfoDiaForm | undefined = undefined
  const editMatInfoDiaState = reactive<EditMatInfoDiaState>({
    visiable: false,
    quickAddTagVisiable: false,
    addTagValue: '',
    tagList: [],
    classifyTreeData: [],
    currentMaterial: undefined,
    formData: {
      title: '',
      description: '',
      tags: [],
      type: MaterialType.IMAGE,
      itype: MaterialSecType.NONE,
      usage: MaterialUsage.MEDIA,
      structure: MaterialStucture.UNKNOW,
    },
  })

  /**
   * 根据输入内容搜索标签
   */
  const searchTags = debounce(async (searchValue: string) => {
    const { data } = await searchTagList(searchValue)
    if (data) {
      editMatInfoDiaState.tagList = data.map((tagItem) => {
        return {
          label: tagItem.tagName,
          value: tagItem.tagName,
        }
      })
    }
  }, 300)
  const searchTagListLoading = computed(() =>
    store.getters['global/isOpLoading'](MaterialApi.SEARCH_TAG_LIST)
  )

  /**
   * 获取分类列表树
   */
  const getClassifyList = async () => {
    const { data } = await fetchClassify()
    if (data.childCateGoryList) {
      editMatInfoDiaState.classifyTreeData = data.childCateGoryList.filter(
        (child) => child.type === ClassifyType.IMAGE
      )
    }
  }
  const initEditMatDiaLoading = computed(() =>
    store.getters['global/isOpLoading'](ClassifyApi.GET_CLASSIFY_TREE)
  )
  /**
   * 打开编辑素材信息弹框
   *
   * @param materialItem 当前点击的素材项
   */
  const openEditMatInfoDia = async (materialItem: MaterialItem) => {
    editMatInfoDiaState.currentMaterial = materialItem
    editMatInfoDiaState.formData.title = materialItem.title
    editMatInfoDiaState.formData.tags = materialItem.tags
    editMatInfoDiaState.formData.description = materialItem.description
    editMatInfoDiaState.formData.type = materialItem.type
    editMatInfoDiaState.formData.itype = materialItem.itype
    editMatInfoDiaState.formData.usage = materialItem.usage
    editMatInfoDiaState.formData.structure = materialItem.structure
    editMatInfoDiaState.formData.categories = materialItem.categories?.map(
      (item) => {
        return {
          label: item.name,
          value: item.id,
        }
      }
    )
    oldFormData = cloneDeep(editMatInfoDiaState.formData)
    await getClassifyList()
    editMatInfoDiaState.visiable = true
  }

  /**
   * 打开快速添加标签input
   *
   * @param ref 快速添加标签的input引用
   */
  const openQuickAddTag = async (ref: Ref) => {
    editMatInfoDiaState.quickAddTagVisiable = true
    await nextTick()
    ref.value.focus()
  }

  /**
   * 确认快速添加标签
   */
  const confirmQuickAddTag = async () => {
    const addTagReq: OptionTagReq = {
      tagName: editMatInfoDiaState.addTagValue,
    }
    const { data } = await optionTag(addTagReq)
    message.success('标签添加成功')
    editMatInfoDiaState.formData.tags?.push(data.tagName)
    editMatInfoDiaState.addTagValue = ''
    editMatInfoDiaState.quickAddTagVisiable = false
  }
  const optionTagLoading = computed(() =>
    store.getters['global/isOpLoading'](TagApi.OPTION_TAG)
  )

  /**
   * 确认修改素材信息
   */
  const confirmEditMatInfoDia = async () => {
    if (editMatInfoDiaState.currentMaterial) {
      const chageObj = compareObject<EditMatInfoDiaForm>(
        oldFormData,
        editMatInfoDiaState.formData
      )
      if (chageObj) {
        const { tags, categories, ...resFormData } = chageObj
        const updateMatReqData: UpdateMaterialReq = {
          id: editMatInfoDiaState.currentMaterial.id,
          ...resFormData,
        }
        if (tags) {
          updateMatReqData.tagList = tags || []
        }
        if (categories) {
          updateMatReqData.title = editMatInfoDiaState.formData.title
          updateMatReqData.categoryList =
            categories?.map((item) => item.value) || []
        }
        await updateMatV2(updateMatReqData)
        message.success('修改成功！')
      }
    }
    editMatInfoDiaState.visiable = false
    await searchApi()
  }
  const updateMatV2Loading = computed(() =>
    store.getters['global/isOpLoading'](MaterialApi.UPDATE_MATERIAL_INFO_V2)
  )

  return {
    editMatInfoDiaState,
    openEditMatInfoDia,
    confirmEditMatInfoDia,
    searchTags,
    searchTagListLoading,
    optionTagLoading,
    confirmQuickAddTag,
    openQuickAddTag,
    initEditMatDiaLoading,
    updateMatV2Loading,
  }
}

export default useEditMatInfoDia
